﻿using System.Text;
using System.Text.Json;
using VolcanoEngine.SDK.Utils;

namespace VolcanoEngine.SDK
{
    public class HTTPClient
    {
        private readonly IHttpClientFactory httpClientFactory;
        private readonly VolcanoEngine volcanoEngine;

        public HTTPClient(IHttpClientFactory httpClientFactory, VolcanoEngine volcanoEngine)
        {
            this.httpClientFactory = httpClientFactory;
            this.volcanoEngine = volcanoEngine;
        }

        /// <summary>
        /// HttpClient 实例
        /// </summary>
        private HttpClient httpClient => httpClientFactory.CreateClient();

        /// <summary>
        /// 发送 Post 请求
        /// </summary>
        /// <param name="body">请求提</param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<string> PostAsync(string body, CancellationToken cancellationToken)
        {
            var byteArray = Encoding.UTF8.GetBytes(body);

            var bodyHash = Encry256.ComputeHash256(body);

            var dateTimeSign = DateTime.UtcNow;
            var nowDate = dateTimeSign.ToString("yyyyMMdd");
            var nowTime = dateTimeSign.ToString("HHmmss");
            var dateTimeSignStr = $"{nowDate}T{nowTime}Z";

            using var request = new HttpRequestMessage(HttpMethod.Post, ConstKey.URL)
            {
                Content = new ByteArrayContent(byteArray)
                {
                    Headers =
                    {
                        ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json")
                    }
                }
            };

            // 构建授权头
            var authorization = volcanoEngine.BuildAuthorization(body, nowDate, dateTimeSignStr);

            request.Headers.Add("X-Date", dateTimeSignStr);
            request.Headers.Add("X-Content-Sha256", bodyHash);
            request.Headers.Add("Host", ConstKey.Host);
            request.Headers.UserAgent.ParseAdd($"volc-sdk-dotnet/{ConstKey.Version}");
            request.Headers.TryAddWithoutValidation("Authorization", authorization);

            try
            {
                using var response = await httpClient.SendAsync(request, cancellationToken);
                response.EnsureSuccessStatusCode();

                var responseStr = await response.Content.ReadAsStringAsync(cancellationToken);
                var translations = ParseResponseJson(responseStr);

                return string.Join('\n', translations);
            }
            catch (HttpRequestException ex)
            {
                throw new InvalidOperationException($"API request failed: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 解析响应的 Json 字符串
        /// </summary>
        /// <param name="jsonString">json</param>
        /// <returns></returns>
        private string[] ParseResponseJson(string jsonString)
        {
            using var document = JsonDocument.Parse(jsonString);
            var translationList = document.RootElement.GetProperty("TranslationList");

            var translations = new string[translationList.GetArrayLength()];
            for (var i = 0; i < translations.Length; i++)
            {
                translations[i] = translationList[i].GetProperty("Translation").GetString() ?? string.Empty;
            }

            return translations;
        }

    }
}
